package xyj.sparrow.scheduler.util;


import cn.hutool.core.util.StrUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import xyj.sparrow.scheduler.annotation.Service;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.Map;

public class RpcServiceImplUtil {
    @Autowired
    ApplicationContext applicationContext;
    private final HashMap<String, String> map = new HashMap<>();

    @PostConstruct
    public void init() {
        Map<String, Object> beansWithAnnotation = applicationContext.getBeansWithAnnotation(Service.class);
        for (Map.Entry<String, Object> bean : beansWithAnnotation.entrySet()) {
            Class<?> aClass = bean.getValue().getClass();
            Service annotation = aClass.getAnnotation(Service.class);
            String aliasName = aClass.getName().substring(aClass.getName().lastIndexOf(".") + 1);
            if (annotation != null) {
                aliasName = StrUtil.isBlank(annotation.aliasName()) ? aliasName : annotation.aliasName();
            }
            if (Character.isUpperCase(aliasName.charAt(0))) {
                aliasName = Character.toLowerCase(aliasName.charAt(0)) + aliasName.substring(1);
            }
            map.put(aliasName, aClass.getName());
        }
    }

    public String getRpcServiceImpl(String aliasName) {
        return map.get(aliasName);
    }
}
